<template>
  <div class="project-create-container">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <div class="header-content">
          <h2>{{ isEditMode ? '编辑项目' : '创建项目' }}</h2>
          <p>{{ isEditMode ? '编辑现有API监控项目' : '创建一个新的API监控项目' }}</p>
        </div>
      </template>
    </el-page-header>
    
    <div class="content-container">
      <el-row justify="center">
        <el-col :span="12">
          <el-card class="form-card">
            <template #header>
              <div class="card-header">
                <el-icon><FolderAdd /></el-icon>
                <span>{{ isEditMode ? '编辑项目信息' : '项目信息' }}</span>
              </div>
            </template>
            
            <el-form
              ref="projectFormRef"
              :model="projectForm"
              :rules="rules"
              label-width="100px"
              class="project-form"
            >
              <el-form-item label="项目名称" prop="name">
                <el-input 
                  v-model="projectForm.name" 
                  placeholder="请输入项目名称"
                  clearable
                />
              </el-form-item>
              
              <el-form-item label="项目描述" prop="description">
                <el-input
                  v-model="projectForm.description"
                  placeholder="请输入项目描述"
                  type="textarea"
                  :rows="4"
                />
              </el-form-item>
              
              <el-form-item label="项目图标" prop="iconUrl">
                <div class="avatar-uploader">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleAvatarUpload"
                  >
                    <el-avatar 
                      v-if="projectForm.iconUrl" 
                      :size="80" 
                      :src="projectForm.iconUrl" 
                      shape="square"
                    />
                    <el-avatar 
                      v-else 
                      :size="80" 
                      shape="square"
                      class="default-avatar"
                    >
                      <el-icon :size="32"><Upload /></el-icon>
                    </el-avatar>
                  </el-upload>
                  <div class="avatar-tip">点击上传项目图标</div>
                </div>
              </el-form-item>
              
              <el-form-item>
                <div class="form-actions">
                  <el-button @click="goBack">取消</el-button>
                  <el-button 
                    type="primary" 
                    @click="submitForm" 
                    :loading="submitting"
                  >
                    {{ isEditMode ? '更新项目' : '创建项目' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { reactive, ref, inject, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { FolderAdd, Upload } from '@element-plus/icons-vue'
import api from '../services/api'

export default {
  name: 'ProjectCreate',
  components: {
    FolderAdd,
    Upload
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const projectFormRef = ref(null)
    const refreshProjects = inject('refreshProjects') // 注入刷新项目列表的方法
    
    // 检查是否为编辑模式
    const isEditMode = ref(false)
    const projectId = ref(null)
    
    const projectForm = reactive({
      name: '',
      description: '',
      iconUrl: ''
    })
    
    const submitting = ref(false)
    const uploadedFile = ref(null) // 保存上传的文件
    
    const rules = {
      name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      description: [
        { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
      ]
    }
    
    // 获取项目详情（编辑模式）
    const fetchProject = async () => {
      if (!isEditMode.value) return
      
      try {
        const response = await api.get(`/projects/${projectId.value}`)
        const project = response.data
        projectForm.name = project.name
        projectForm.description = project.description
        projectForm.iconUrl = project.iconUrl || ''
      } catch (error) {
        ElMessage.error('获取项目信息失败: ' + error.message)
      }
    }
    
    // 组件挂载时检查是否为编辑模式
    onMounted(() => {
      if (route.name === 'ProjectEdit' && route.params.id) {
        isEditMode.value = true
        projectId.value = route.params.id
        fetchProject()
      }
    })
    
    // 返回项目列表
    const goBack = () => {
      router.push('/')
    }
    
    // 处理头像上传
    const handleAvatarUpload = async (options) => {
      const { file } = options
      uploadedFile.value = file // 保存文件以备后续上传
      
      // 显示预览
      const reader = new FileReader()
      reader.onload = (e) => {
        projectForm.iconUrl = e.target.result
        ElMessage.success('图标已选择，保存项目后将上传到云端')
      }
      reader.readAsDataURL(file)
    }
    
    // 上传前检查
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过 2MB!')
      }
      
      return isJPG && isLt2M
    }
    
    // 提交表单
    const submitForm = async () => {
      projectFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            if (isEditMode.value) {
              // 编辑模式 - 更新项目
              const projectData = {
                name: projectForm.name,
                description: projectForm.description
              }
              
              const response = await api.put(`/projects/${projectId.value}`, projectData)
              const updatedProject = response.data
              
              // 如果有上传的文件，则上传图标到七牛云
              if (uploadedFile.value) {
                const formData = new FormData()
                formData.append('file', uploadedFile.value)
                
                const iconResponse = await api.post(`/projects/${updatedProject.id}/icon`, formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
                })
                
                // 更新项目图标URL
                updatedProject.iconUrl = iconResponse.data
              }
              
              ElMessage.success('更新项目成功')
            } else {
              // 创建模式 - 创建项目
              const projectData = {
                name: projectForm.name,
                description: projectForm.description
              }
              
              const response = await api.post('/projects', projectData)
              const createdProject = response.data
              
              // 如果有上传的文件，则上传图标到七牛云
              if (uploadedFile.value) {
                const formData = new FormData()
                formData.append('file', uploadedFile.value)
                
                const iconResponse = await api.post(`/projects/${createdProject.id}/icon`, formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data'
                  }
                })
                
                // 更新项目图标URL
                createdProject.iconUrl = iconResponse.data
              }
              
              ElMessage.success('创建项目成功')
            }
            
            // 刷新项目列表
            if (refreshProjects) {
              refreshProjects()
            }
            router.push('/')
          } catch (error) {
            console.error(`${isEditMode.value ? '更新' : '创建'}项目失败:`, error.response || error.message)
            ElMessage.error(`${isEditMode.value ? '更新' : '创建'}项目失败: ` + (error.response?.data?.message || error.message))
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    return {
      projectFormRef,
      projectForm,
      rules,
      submitting,
      isEditMode,
      goBack,
      handleAvatarUpload,
      beforeAvatarUpload,
      submitForm
    }
  }
}
</script>

<style scoped>
.project-create-container {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  background-color: #f0ebe0;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid #e0d4b4;
}

.header-content h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #5a4a3a;
}

.header-content p {
  margin: 4px 0 0 0;
  color: #7a6b5a;
  font-size: 14px;
}

.content-container {
  padding: 0 24px;
}

.form-card {
  border: 1px solid #e0d4b4;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.project-form {
  padding: 20px 0;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.default-avatar {
  background-color: #f5f5f5;
  cursor: pointer;
}

.avatar-tip {
  color: #999;
  font-size: 12px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

:deep(.el-card__header) {
  border-bottom: 1px solid #e0d4b4;
  padding: 16px 20px;
}
</style>